<!-- 自定义设置 -->
<template>
  <span class="settings-wrap">
    <el-tabs :tab-position="tabPosition">
      <el-tab-pane label="查询条件">
        <search-field :field-list="searchData"
                      @checked="searchChecked" />
      </el-tab-pane>
      <el-tab-pane label="表格列">
        <table-field :field-list="tableData"
                     @checked="tabelChecked" />
      </el-tab-pane>
      <!-- <el-tab-pane label="导出字段">
        <ExportField :field-list="exportData"
                     @checked="exportChecked" />
      </el-tab-pane> -->
    </el-tabs>
    <!-- 按钮 -->
    <div class="dialog-footer">
      <!-- <el-button @click="setupVisible = false">取 消</el-button> -->
      <el-button @click="recoveryDefault">恢复默认值</el-button>
      <el-button type="primary"
                 :loading="loading"
                 @click="submit">{{
          loading ? "提交中 ..." : "确 定"
        }}</el-button>
    </div>
    <!-- </el-dialog> -->
  </span>
</template>

<script>
import { mapState } from "vuex";
import settingsApi from "@/api/modules/login";
import SearchField from './components/SearchField.vue'
import TableField from './components/TableField.vue'
// import ExportField from './components/ExportField.vue'
import { clearMenuMap } from "@menu";

export default {
  name: 'SettingsWrap',
  inject: ['reload'],
  components: { SearchField, TableField },
  data () {
    return {
      tabPosition: 'left',
      allChecked: false,
      /* 后端需要前端拼接结构 */
      standard: {
        data: {}
      },
      searchData: [],
      tableData: [],
      exportData: [],
      resourceId: null,
      loading: false,
      // setupVisible: false
    }
  },
  computed: {
    ...mapState({
      menu: (state) => state.menu.menu
    }),
    isNotSelectionOrAction () {
      return item => item.type !== 'selection';
    },
    addAttribute () {
      return (data = [], babel = false) => {
        const shouldCheck = (item) => item.name === 'contractNo' || item.type === 'action';
        return data
          .filter(pos => pos.name || pos.control || pos.label)
          .map(item => ({
            ...item,
            // fixed: shouldCheck(item) ? true : babel,
            checked: shouldCheck(item) ? true : babel
          }))
          .filter(this.isNotSelectionOrAction);
      };
    },
    transformField () {
      return (newData, oldData) => {
        if (!newData) {
          return []
        }
        const newLabels = new Set(newData?.map(pos => pos.label));
        const shouldCheck = (item) => item.name === 'contractNo' || item.type === 'action';
        return oldData
          .map(item => ({
            ...item,
            fixed: shouldCheck(item) ? true : false,
            checked: newLabels.has(item.label)
          }))
          .filter(this.isNotSelectionOrAction);
      };
    },
    transformParams () {
      return (bar, tab) => {
        let { data } = this.standard
        data.filters = this.fieldFilter(bar)
        data.columns = this.fieldFilter(tab)
        return {
          resourceId: this.resourceId,
          ...this.standard
        }
      }
    },
    fieldFilter () {
      return (filterBar) => {
        return filterBar
          ?.filter(pos => pos.checked)
          .map(item => {
            return item.hidden
              ? { ...item, hidden: false }
              : { ...item }
          })
      }
    }
  },
  created () {
    this.load()
  },
  beforeDestroy () {
    this.$once("hook:beforeDestroy", () => clearInterval(this.timer));
  },
  methods: {
    async load () {
      let response = await settingsApi.dynamicSettings(this.menu.menuId)
      this.standard.data = response?.data?.customize || response?.data?.standard
      this.resourceId = response?.data?.resourceId;
      console.log('response', response.data)
      if (response?.data?.customize) {
        // 修改过后的数据
        let newData = response?.data?.customize
        //  固定数据
        let oldData = response?.data?.standard
        this.searchData = this.transformField(newData?.filters, oldData?.filters)
        this.tableData = this.transformField(newData?.columns, oldData?.columns)
        console.log('固定的列数据', this.tableData)
        // this.exportData = this.transformField(newData?.exports, oldData?.exports)
      } else {
        this.searchData = this.addAttribute(this.standard.data.filters, true)
        /* 过滤表格操作按钮 */
        this.tableData = this.addAttribute(this.standard.data.columns, true)
        console.log('不是固定的数据', this.tableData)
        // this.exportData = this.addAttribute(this.standard.data.exports, true)
      }
    },
    searchChecked (value) {
      this.searchData = this.addAttribute(this.searchData, value)
    },
    tabelChecked (value) {
      this.tableData = this.addAttribute(this.tableData, value)
    },
    // exportChecked (value) {
    //   this.exportData = this.addAttribute(this.exportData, value)
    // },
    submit () {
      this.loading = true;
      this.timer = setTimeout(() => {
        setTimeout(() => {
          this.handelSave();
          this.loading = false;
        }, 400);
      }, 1500);
    },
    /* 保存 */
    handelSave () {
      let transformParams = this.transformParams(this.searchData, this.tableData, this.resourceId)
      let response = settingsApi.dynamicSettingsSave(transformParams)
      console.log(response)
      clearMenuMap()
      this.reload()
      this.$message.success('操作成功！');
      this.$emit("confirm");
    },
    // 恢复默认值
    recoveryDefault () {
      this.$message("功能开发中，敬请期待！");
    }
  }
}
</script>

<style scoped>
.dialog-sync >>> .el-dialog__header {
  text-align: left;
}
.dialog-sync >>> .el-dialog__body {
  max-height: 300px;
}
.dialog-sync >>> .el-dialog__footer {
  text-align: center;
}
.dialog-footer {
  padding: 20px 20px 0 20px;
}
</style>